<?php
/**
 * 万能WiFi模块微站定义
 *
 * @author junsion
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');
define("RES", "../addons/junsion_wifinav/template/");
class junsion_wifinavModuleSite extends WeModuleSite {
	
	public function doWebUser(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
		if (!empty($_GPC['keyword'])){
				$condition = " and (nickname like '%{$_GPC['keyword']}%' or realname like '%{$_GPC['keyword']}%')";
			}
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_user')." WHERE weid = '{$_W['weid']}' {$condition} LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_user') . " WHERE weid = '{$_W['uniacid']}' {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			//查找是否存在
			$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_user')." WHERE id = :id and weid = :weid" , array(':id' => $id, ':weid'=>$weid));
			if (empty($item)) {
				message('数据不存在！', '', 'error');
			}
			if(checksubmit('submit')){//检测是否post
				$data = array(
						'weid'=>$_W['uniacid'],
				);
				pdo_update($this->modulename.'_user', $data, array('id'=>$id));//添加数据
				message('用户更新成功！', $this->createWebUrl('applet', array('op' => 'display')), 'success');
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_user')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('用户不存在！');
			}
		
			pdo_delete($this->modulename.'_user', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('user');
	}
	
	public function doWebDistributor(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			if (!empty($_GPC['keyword'])){
				$condition = " and (nickname like '%{$_GPC['keyword']}%' or realname like '%{$_GPC['keyword']}%')";
			}
			$condition .= " and distributor>0";
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_user')." WHERE weid = '{$_W['weid']}' {$condition} LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_user') . " WHERE weid = '{$_W['uniacid']}' {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'audit'){
			$id = $_GPC['id'];
			$res = pdo_query('update '.tablename($this->modulename.'_user')." set distributor = 3-distributor where id='{$id}' and weid='{$weid}'");
			if ($res) die('1');
			else die('0');
		}
		include $this->template('distributor');
	}
	
	public function doWebSlider(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			if (checksubmit('submit')){
				$sorts = $_GPC['sort'];
				foreach ($sorts as $id=>$sort){
					pdo_update($this->modulename.'_slider', array('sort'=>$sort), array('id'=>$id));
				}
				message('批量更改排序成功',referer(),'success');
			}
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_slider')." WHERE weid = '{$_W['weid']}' order by sort desc  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_slider') . " WHERE weid = '{$_W['uniacid']}'");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_slider')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				if (empty($_GPC['thumb'])) {
					message('图片不能为空!');
				}
				$data = array(
						'weid'=>$_W['uniacid'],
						'title'=>$_GPC['title'],
						'thumb'=>$_GPC['thumb'],
						'qrcode'=>$_GPC['qrcode'],
						'qrdes'=>$_GPC['qrdes'],
						'path'=>$_GPC['path'],
						'appid'=>$_GPC['appid'],
						'type'=>$_GPC['type'],
						'status'=>$_GPC['status'],
						'sort'=>$_GPC['sort'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_slider', $data);//添加数据
					message('幻灯片添加成功！', $this->createWebUrl('slider', array('op' => 'display')), 'success');
				}else{
					pdo_update($this->modulename.'_slider', $data, array('id' => $id));
					message('幻灯片更新成功！', $this->createWebUrl('slider', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_slider")." set status = !status where id='{$id}'");
			die('1');
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_slider')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('幻灯片不存在！');
			}
				
			pdo_delete($this->modulename.'_slider', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('slider');
	}
	
	public function doWebRecommend(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			if (checksubmit('submit')){
				$sorts = $_GPC['sort'];
				foreach ($sorts as $id=>$sort){
					pdo_update($this->modulename.'_recommend', array('sort'=>$sort), array('id'=>$id));
				}
				message('批量更改排序成功',referer(),'success');
			}
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_recommend')." WHERE weid = '{$_W['weid']}' order by sort desc  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_recommend') . " WHERE weid = '{$_W['uniacid']}'");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_recommend')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				if (empty($_GPC['thumb'])) {
					message('图片不能为空!');
				}
				if (empty($_GPC['qrcode']) && $_GPC['type']==2) {
					message('小程序二维码不能为空!');
				}
				if (empty($_GPC['path']) && $_GPC['type']==1) {
					message('连接不能为空!');
				}
				$data = array(
						'weid'=>$_W['uniacid'],
						'thumb'=>$_GPC['thumb'],
						'qrcode'=>$_GPC['qrcode'],
						'qrdes'=>$_GPC['qrdes'],
						'path'=>$_GPC['path'],
						'appid'=>$_GPC['appid'],
						'type'=>$_GPC['type'],
						'status'=>$_GPC['status'],
						'title'=>$_GPC['title'],
						'color'=>$_GPC['color'],
						'des'=>$_GPC['des'],
						'sort'=>$_GPC['sort'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_recommend', $data);//添加数据
					message('推荐添加成功！', $this->createWebUrl('recommend', array('op' => 'display')), 'success');
				}else{
					pdo_update($this->modulename.'_recommend', $data, array('id' => $id));
					message('推荐更新成功！', $this->createWebUrl('recommend', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_recommend")." set status = !status where id='{$id}'");
			die('1');
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_recommend')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('推荐不存在！');
			}
			
			pdo_delete($this->modulename.'_recommend', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('recommend');
	}
	
	public function doWebCategory(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			if (checksubmit('submit')){
				$sorts = $_GPC['sort'];
				foreach ($sorts as $id=>$sort){
					pdo_update($this->modulename.'_category', array('sort'=>$sort), array('id'=>$id));
				}
				message('批量更改排序成功',referer(),'success');
			}
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_category')." WHERE weid = '{$_W['weid']}' order by sort desc  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_category') . " WHERE weid = '{$_W['uniacid']}'");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_category')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				if (empty($_GPC['title'])) {
					message('标题不能为空!');
				}
				$data = array(
						'weid'=>$_W['uniacid'],
						'title'=>$_GPC['title'],
						'sort'=>$_GPC['sort'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_category', $data);//添加数据
					message('分类添加成功！', $this->createWebUrl('category', array('op' => 'display')), 'success');
				}else{
					pdo_update($this->modulename.'_category', $data, array('id' => $id));
					message('分类更新成功！', $this->createWebUrl('category', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_category')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('分类不存在！');
			}
		
			pdo_delete($this->modulename.'_category', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('category');
	}
	
	public function doWebApplet(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display' || $op == 'post'){
			$category = pdo_fetchall('select * from '.tablename($this->modulename.'_category')." where weid='{$weid}'",array(),'id');
			if (empty($category)){
				message('请先添加分类！', $this->createWebUrl('category', array('op' => 'post')), 'error');
			}
		}
		if($op == 'display'){
			if (checksubmit('submit')){
				$sorts = $_GPC['sort'];
				foreach ($sorts as $id=>$sort){
					pdo_update($this->modulename.'_applet', array('sort'=>$sort), array('id'=>$id));
				}
				message('批量更改排序成功',referer(),'success');
			}
			if ($_GPC['aid']) $condition .= " and id='{$_GPC['aid']}'";
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_applet')." WHERE weid = '{$_W['weid']}' and status>=0 {$condition} order by sort desc  LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_applet') . " WHERE weid = '{$_W['uniacid']}' and status>=0 {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				//查找是否存在
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_applet')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				if (empty($_GPC['thumb'])) {
					message('图片不能为空!');
				}
				if (empty($_GPC['qrcode']) && $_GPC['type']==2) {
					message('小程序二维码不能为空!');
				}
				if (empty($_GPC['path']) && $_GPC['type']==1) {
					message('连接不能为空!');
				}
				$data = array(
						'weid'=>$_W['uniacid'],
						'cid'=>$_GPC['cid'],
						'title'=>$_GPC['title'],
						'des'=>$_GPC['des'],
						'thumb'=>$_GPC['thumb'],
						'qrcode'=>$_GPC['qrcode'],
						'qrdes'=>$_GPC['qrdes'],
						'path'=>$_GPC['path'],
						'appid'=>$_GPC['appid'],
						'type'=>$_GPC['type'],
						'status'=>$_GPC['status'],
						'sort'=>$_GPC['sort'],
						'bgcolor'=>$_GPC['bgcolor'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_applet', $data);//添加数据
					message('小程序添加成功！', $this->createWebUrl('applet', array('op' => 'display')), 'success');
				}else{
					pdo_update($this->modulename.'_applet', $data, array('id' => $id));
					message('小程序更新成功！', $this->createWebUrl('applet', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'status'){
			$id = $_GPC['id'];
			pdo_query('update '.tablename($this->modulename."_applet")." set status = !status where id='{$id}'");
			die('1');
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_applet')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('推荐不存在！');
			}
				
			pdo_delete($this->modulename.'_applet', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('applet');
	}
	
	public function doWebList(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and SSID like '%{$_GPC['keyword']}%'";
			}
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_list')." WHERE weid = '{$_W['weid']}' and status>0 {$condition} LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_list') . " WHERE weid = '{$_W['uniacid']}' and status>0 {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			//查找是否存在
			if (!empty($id)){
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_list')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				$data = array(
						'BSSID' => $_GPC['BSSID'],
						'password' => $_GPC['password'],
						'SSID' => $_GPC['SSID'],
						'status'=>$_GPC['status'],
				);
				if (!empty($item)){
					pdo_update($this->modulename.'_list', $data, array('id' => $id));
					message('更新成功！', $this->createWebUrl('list', array('op' => 'display')), 'success');
				}else{
					pdo_insert($this->modulename.'_list', $data);
					message('添加成功！', $this->createWebUrl('list', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_list')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('WiFi不存在！');
			}
		
			pdo_delete($this->modulename.'_list', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}elseif ($op == 'qrcode'){
			$id = intval($_GPC['id']);
			$item = pdo_fetch('select id,qrcode,SSID from '.tablename($this->modulename.'_list')." where id='{$id}'");
			if (empty($item)) message('wifi不存在',referer(),'error');
			$qr = $this->createQrcode($item['id']);
			header('Content-type: image/jpeg');
			header("Content-Disposition: attachment; filename={$item['SSID']}.jpg");
			readfile($qr);
			exit;
		}elseif ($op == 'allQrcode'){
			set_time_limit(0);
			$list = pdo_fetchall("SELECT id,qrcode,SSID FROM ".tablename($this->modulename.'_list')." WHERE weid = '{$_W['uniacid']}' and uid!=0 ");//分页
			//小程序二维码为空则重新生成
			set_time_limit(0);
			foreach ($list as $v){
				$qrList[] = $this->createQrcode($v['id']);
			}
			if (!empty($qrList)){
				$this->createZip($qrList);
			}
			exit;
		}
		include $this->template('list');
	}
	
	private function uploadQiniu($url,$cfg,$type = '.png'){//$url 要上传的图片的链接 $cfg 七牛参数
		global $_GPC, $_W;
		require_once IA_ROOT. '/addons/junsion_wifinav/qiniu.php';
		$cfg['url'] = $cfg['qiniuUrl'];
		$qiniu = new Qiniu();
		$res = $qiniu->save($url, $cfg,$type);
		return $res;
	}
	
	public function doWebAOrder(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$time = time() - 3600; 
			pdo_query('delete from '.tablename($this->modulename.'_aorder')." where status=0 and paytime<".$time);
			$type = $_GPC['type'];
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and ordersn like '%{$_GPC['keyword']}%'";
			}
			if($type==1) $condition .= " and type=2";
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_aorder')." WHERE weid = '{$_W['uniacid']}' and status=1 {$condition} order by paytime desc LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			if ($list){
				$uids = array();
				$pids = array();
				$aids = array();
				foreach ($list as $v){
					if(!in_array($v['uid'], $uids)) $uids[] = $v['uid'];
					if(!in_array($v['pid'], $pids)) $pids[] = $v['pid'];
					if(!in_array($v['aid'], $aids)) $aids[] = $v['aid'];
				}
				$user = pdo_fetchall('select avatar,id,nickname from '.tablename($this->modulename.'_user')." where id in (".implode(',', $uids).")",array(),'id');
				$packages = pdo_fetchall('select id,title from '.tablename($this->modulename.'_apps')." where id in (".implode(',', $pids).")",array(),'id');
				$apps = pdo_fetchall('select id,title from '.tablename($this->modulename.'_applet')." where id in (".implode(',', $aids).")",array(),'id');
			}
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_aorder') . " WHERE weid = '{$_W['uniacid']}' and {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}
		include $this->template('aorder');
	}
	
	public function doWebOrder(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			pdo_query('delete from '.tablename($this->modulename.'_order')." where status=0 and paytime<".$time);
			$type = $_GPC['type'];
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and (SSID like '%{$_GPC['keyword']}%' or ordersn like '%{$_GPC['keyword']}%')";
			}
			if($type==1) $condition .= " and type=2";
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_order')." WHERE weid = '{$_W['uniacid']}' and status=1 {$condition} order by paytime desc LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			if ($list){
				$uids = array();
				$pids = array();
				foreach ($list as $v){
					if(!in_array($v['uid'], $uids)) $uids[] = $v['uid'];
					if(!in_array($v['pid'], $pids)) $pids[] = $v['pid'];
				}
				$user = pdo_fetchall('select avatar,id,nickname from '.tablename($this->modulename.'_user')." where id in (".implode(',', $uids).")",array(),'id');
				$packages = pdo_fetchall('select id,title from '.tablename($this->modulename.'_package')." where id in (".implode(',', $pids).")",array(),'id');
			}
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_order') . " WHERE weid = '{$_W['uniacid']}' and {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}
		include $this->template('order');
	}
	
	public function doWebPackage(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and title like '%{$_GPC['keyword']}%'";
			}
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_package')." WHERE weid = '{$_W['uniacid']}' {$condition} LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_package') . " WHERE weid = '{$_W['uniacid']}' and {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_package')." WHERE id = :id" , array(':id' => $id));
			if(checksubmit('submit')){//检测是否post
				$data = array(
						'price' => $_GPC['price'],
						'title' => $_GPC['title'],
						'day' => $_GPC['day'],
				);
				if ($item){
					pdo_update($this->modulename.'_package', $data, array('id' => $id));
					message('更新成功！', $this->createWebUrl('package', array('op' => 'display')), 'success');
				}else{
					$data['weid'] = $weid;
					pdo_insert($this->modulename.'_package', $data);
					message('添加成功！', $this->createWebUrl('package', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_package')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('套餐不存在！');
			}
		
			pdo_delete($this->modulename.'_package', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('package');
	}
	
	public function doWebApps(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and title like '%{$_GPC['keyword']}%'";
			}
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_apps')." WHERE weid = '{$_W['uniacid']}' {$condition} LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_apps') . " WHERE weid = '{$_W['uniacid']}' and {$condition}");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_apps')." WHERE id = :id" , array(':id' => $id));
			if(checksubmit('submit')){//检测是否post
				$data = array(
						'price' => $_GPC['price'],
						'title' => $_GPC['title'],
						'day' => $_GPC['day'],
				);
				if ($item){
					pdo_update($this->modulename.'_apps', $data, array('id' => $id));
					message('更新成功！', $this->createWebUrl('apps', array('op' => 'display')), 'success');
				}else{
					$data['weid'] = $weid;
					pdo_insert($this->modulename.'_apps', $data);
					message('添加成功！', $this->createWebUrl('apps', array('op' => 'display')), 'success');
				}
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_apps')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('套餐不存在！');
			}
	
			pdo_delete($this->modulename.'_apps', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}
		include $this->template('apps');
	}
	
	public function doWebEnter(){
		global $_W,$_GPC;
		$op = $_GPC['op']?$_GPC['op']:'display';
		$weid = $_W['uniacid'];
		if($op == 'display'){
			$pindex = max(1, intval($_GPC['page']));
			$psize =20;//每页显示
			if (!empty($_GPC['keyword'])){
				$condition = " and SSID like '%{$_GPC['keyword']}%'";
			}
			if ($_GPC['id']) $condition = " and BSSID='{$_GPC['id']}'";
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_list')." WHERE weid = '{$_W['uniacid']}' and uid!=0 {$condition} order by status LIMIT ".($pindex - 1) * $psize.','.$psize);//分页
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->modulename.'_list') . " WHERE weid = '{$_W['uniacid']}' and uid!=0 {$condition}");
			$pager = pagination($total, $pindex, $psize);
			$package = pdo_fetchall('select id,title from '.tablename($this->modulename.'_package')." where weid='{$weid}'");
			if (!empty($list)){
				$uids = array();
				foreach ($list as $l){
					if (!in_array($l['uid'],$uids)) $uids[] = $l['uid'];
				}
				$users = pdo_fetchall('select id,nickname,avatar from '.tablename($this->modulename.'_user')." where id in (".implode(',', $uids).")",array(),'id');
			}
			
		}elseif ($op == 'post'){
			$id = intval($_GPC['id']);
			//查找是否存在
			$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_list')." WHERE id = :id" , array(':id' => $id));
			if (empty($item)) {
				message('数据不存在！', '', 'error');
			}
			if(checksubmit('submit')){//检测是否post
				$data = array(
					'realname' => $_GPC['realname'],
					'mobile' => $_GPC['mobile'],
					'stitle' => $_GPC['stitle'],
					'BSSID' => $_GPC['BSSID'],
					'SSID' => $_GPC['SSID'],
					'password' => $_GPC['password'],
					'status'=>$_GPC['status'],
					'advPic'=>$_GPC['advPic'],
				);
				if ($data['advPic']){
					if (strpos($data['advPic'], 'http://') === false && strpos($data['advPic'], 'https://') === false){
						$cfg = $this->module['config'];
						$img = toimage($data['advPic']);
						if ($cfg['qiniu']['isqiniu']){//七牛存储
							$img = $this->uploadQiniu($img,$cfg['qiniu'],'.jpg');
						}elseif (!empty($_W['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
							$rand = random(10).time();
							$filename = $rand."pic.jpg";
							load()->func('file');
							$dir = ATTACHMENT_ROOT."images/";
							rename($url, $dir.$filename);
							file_remote_upload('images/'.$filename); //上传图片到远程
							$img = tomedia('images/'.$filename);
						}
						$data['advPic'] = $img;
					}
				}
				pdo_update($this->modulename.'_list', $data, array('id' => $id));
				message('更新成功！', $this->createWebUrl('enter', array('op' => 'display')), 'success');
			}
		}else if($op == 'del'){
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id FROM ".tablename($this->modulename.'_list')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('WiFi不存在！');
			}
		
			pdo_delete($this->modulename.'_list', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}else if($op == 'audit'){
			$id = intval($_GPC['id']);
			$res = pdo_update($this->modulename.'_list',array('status'=>1),array('id'=>$id,'weid'=>$weid));
			if ($res) echo '1';
			else echo '0';
			exit;
		}else if($op == 'status'){
			$id = intval($_GPC['id']);
			$w = pdo_fetch('select id,advStatus,`day`,endtime,newAdvPic from '.tablename($this->modulename.'_list')." where id='{$id}'");
			if (empty($w)) message('记录不存在',referer(),'error');
			if($w['advStatus']){
				pdo_update($this->modulename.'_list',array('advStatus'=>0),array('id'=>$id,'weid'=>$weid));
			}else{
				$day = $w['day'];
				if ($day>0){
					$time = time();
					if($time<$wifi['endtime']){
						//未过期
						$t = $day*24*3600;
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t}, day=0 where id='{$w['id']}'");
					}else{
						//已过期
						$t = strtotime('+ '.$day.'day');
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t}, day=0 where id='{$w['id']}'");
					}
				}
				pdo_update($this->modulename.'_list',array('advStatus'=>1,'advPic'=>$w['newAdvPic'],'newAdvPic'=>''),array('id'=>$id,'weid'=>$weid));
			}
			message('更新图片审核状态成功',referer(),'success');
		}elseif ($op == 'renew'){
			if(checksubmit('submit')){
				$pid = $_GPC['pid'];
				$id = $_GPC['id'];
				$pack = pdo_fetch('select id,price,day from '.tablename($this->modulename.'_package')." where id='{$pid}' and weid='{$weid}'");
				if(empty($pack)) message('套餐不存在', referer(), 'error');
				$wifi = pdo_fetch('select id,uid,endtime,BSSID,SSID from '.tablename($this->modulename.'_list')." where id='{$id}' and weid='{$weid}'");
				if(empty($wifi['uid'])) message('WiFi不存在', referer(), 'error');
				$time = time();
				$order = array(
						'uid' => $wifi['uid'],
						'BSSID' => $wifi['BSSID'],
						'SSID' => $wifi['SSID'],
						'status' =>1,
						'transid' => '后台续费',
						'paytime' => $time,
						'weid' => $weid,
						'pid' => $pid,
						'fee' => $pack['price'],
						'ordersn' => date('YmdHis').random(5,1)
				);
				pdo_insert($this->modulename.'_order',$order);
				$day = $pack['day'];
				if($time<$wifi['endtime']){
					//未过期
					$t = $day*24*3600;
					pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t} where id='{$wifi['id']}'");
				}else{
					//已过期
					$t = strtotime('+ '.$day.'day');
					pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t} where id='{$wifi['id']}'");
				}
				message('续费成功！', $this->createWebUrl('enter', array('op' => 'display')), 'success');
			}
		}
		include $this->template('enter');
	}
	
	public function doWebFooter(){
		global $_W,$_GPC;
		$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		if('post' == $op){
			$id = intval($_GPC['id']);
			if(!empty($id)){
				$item = pdo_fetch("SELECT * FROM ".tablename($this->modulename.'_footer')." WHERE id = :id" , array(':id' => $id));
				if (empty($item)) {
					message('数据不存在！', '', 'error');
				}
			}
			if(checksubmit('submit')){//检测是否post
				$title = trim($_GPC['title']);//菜单名称
				if (empty($title)) {
					message('菜单名称不能为空!');
				}
	
				$data = array(
						'weid'=>$_W['uniacid'],
						'title'=>$title,
						'appid'=>$_GPC['appid'],
						'thumb'=>$_GPC['thumb'],
						'url'=>$_GPC['url'],
						'displayorder'=>$_GPC['displayorder'],
				);
				if(empty($id)){
					pdo_insert($this->modulename.'_footer', $data);//添加数据
					message('菜单添加成功！', $this->createWebUrl('footer', array('op' => 'display')), 'success');
				}else{
					$t = "'{$title}'";
					if ($title != $item['title']){
						$t = "修改菜单名'".$item['title']."'为'".$title."'";
					}
					pdo_update($this->modulename.'_footer', $data, array('id' => $id));
					message('菜单更新成功！', $this->createWebUrl('footer', array('op' => 'display')), 'success');
				}
			}
		}else if('del' == $op){//删除数据
			//权限限制
			$id = intval($_GPC['id']);
			$row = pdo_fetch("SELECT id,title FROM ".tablename($this->modulename.'_footer')." WHERE id = :id", array(':id' => $id));
			if (empty($row)) {
				message('菜单不存在！');
			}
			pdo_delete($this->modulename.'_footer', array('id' => $id));
			message('删除成功！', referer(), 'success');
		}else if('display'==$op){
			$list = pdo_fetchall("SELECT * FROM ".tablename($this->modulename.'_footer')." WHERE weid = '{$_W['weid']}' order by displayorder desc");//分页
		}
		include $this->template('footer');
	}
	
	public function payResult($params){
		global $_W;
		if ($params['from'] == 'notify'){
			$a = substr( $params['tid'], 0, 1 );
			if ($a == 'A'){//红包订单
				$order = pdo_fetch('select id,aid from '.tablename($this->modulename.'_aorder')." where ordersn='{$params['tid']}' and weid='{$_W['uniacid']}'");
			}else $order = pdo_fetch('select * from '.tablename($this->modulename.'_order')." where ordersn='{$params['tid']}' and weid='{$_W['uniacid']}'");
			if ($order['status']) return;
			$res = $this->checkWechatTran($_W['uniacid'], $params['tag']['transaction_id']);
			file_put_contents(IA_ROOT."/addons/junsion_wifinav/pay", date('Y-m-d H:i:s')."： params:".json_encode($params)." res:".json_encode($res)."\n",FILE_APPEND);
			if ($res['code']==1 && $res['fee'] == $order['fee']){
				$update = array('status'=>1,'transid'=>$params['tag']['transaction_id'],'paytime'=>time());
				if ($a == 'A'){
					pdo_update($this->modulename."_aorder",$update,array('id'=>$order['id']));
					pdo_update($this->modulename."_applet",array('status'=>1),array('id'=>$order['aid']));
					return;
				}
				pdo_update($this->modulename.'_order',$update,array('id'=>$order['id']));
				$cfg = $this->module['config'];
				if($order['type']==2){
					$distributor = $cfg['distributor'];
					if($distributor['autoaudit']==1) pdo_update($this->modulename."_user",array('distributor'=>2),array('id'=>$order['uid']));
					else pdo_update($this->modulename."_user",array('distributor'=>1),array('id'=>$order['uid']));
				}else{
					$autoaudit = $cfg['autoaudit'];
					$day = pdo_fetchcolumn('select day from '.tablename($this->modulename.'_package')." where id='{$order['pid']}'");
					$wifi = pdo_fetch('select id,endtime from '.tablename($this->modulename.'_list')." where BSSID='{$order['BSSID']}' and weid='{$_W['uniacid']}'");
					if ($wifi){
						if ($order['type'] == 1){
							pdo_update($this->modulename.'_list',array(
									'realname' => $order['realname'],
									'mobile' => $order['mobile'],
									'stitle' => $order['stitle'],
									'SSID' => $order['SSID'],
									'password' => $order['password'],
									'newAdvPic' => $order['advPic'],
									'advStatus' => 0,
									'day' => $day,
							),array('id'=>$wifi['id']));
							$isupdate = true;
						}else{
							$time = time();
							if($time<$wifi['endtime']){
								//未过期
								$t = $day*24*3600;
								pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t},advStatus'=1,'advPic'='{$order['advPic']}',newAdvPic='' where id='{$wifi['id']}'");
							}else{
								//已过期
								$t = strtotime('+ '.$day.'day');
								pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t},advStatus'=1,'advPic'='{$order['advPic']}',newAdvPic='' where id='{$wifi['id']}'");
							}
						}
					}else{
						pdo_insert($this->modulename.'_list',array(
							'realname' => $order['realname'],
							'uid' => $order['uid'],
							'mobile' => $order['mobile'],
							'BSSID' => $order['BSSID'],
							'stitle' => $order['stitle'],
							'SSID' => $order['SSID'],
							'password' => $order['password'],
							'newAdvPic' => $order['advPic'],
							'advStatus' => 0,
							'day' => $day,
							'status' => $autoaudit?1:0,
							'weid' => $_W['uniacid'],
						));
						$wifi['id'] = pdo_insertid();
						$isupdate = true;
					}
					
					//存在佣金
					if($order['commission']>0){
						pdo_query('update '.tablename($this->modulename.'_user')." set commission = commission + {$order['commission']} where id='{$order['parentid']}'");
					}
					
					//自动审核
					if($autoaudit && $isupdate){
						$time = time();
						if($time<$wifi['endtime']){
							//未过期
							$t = $day*24*3600;
							pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t}, day=0',advStatus'=1,'advPic'='{$order['advPic']}',newAdvPic='' where id='{$wifi['id']}'");
						}else{
							//已过期
							$t = strtotime('+ '.$day.'day');
							pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t}, day=0,advStatus'=1,'advPic'='{$order['advPic']}',newAdvPic='' where id='{$wifi['id']}'");
						}
					}
				}
			}
		}
	}
	
	private function checkWechatTran($uniacid,$transid){
		$appid = pdo_fetchcolumn('select `key` from ' . tablename('account_wxapp') . " where uniacid = '{$uniacid}'");
		load()->model('payment');
		$setting = uni_setting($_W['uniacid'], array('payment'));
		$options = $setting['payment']['wechat'];
		$url = "https://api.mch.weixin.qq.com/pay/orderquery";
		$random = random(8);
		$post = array(
				'appid'=>$appid,
				'transaction_id'=>$transid,
				'nonce_str'=>$random,
				'mch_id'=>$options['mchid'],
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$options['signkey']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS' || $resp['return_code'] != 'SUCCESS') {
			exit('fail');
		}
		if ($resp['trade_state'] == 'SUCCESS') return array('code'=>1,'fee'=>$resp['total_fee']/100);
	}
	
	private function ToUrlParams($post)
	{
		$buff = "";
		foreach ($post as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	private function ToXml($post)
	{
		$xml = "<xml>";
		foreach ($post as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}
	
	private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		if($useCert == true){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		}
	}
	
	private function createQrcode($id){
		global $_W;
		$path = IA_ROOT.'/addons/junsion_wifinav/pics';
		if(!file_exists($path)){
			mkdir($path,0777);
			if(!file_exists($path)) message('请创建 '.IA_ROOT.'/addons/junsion_wifinav/pics 文件夹并给777权限');
		}
		$path = $path.'/'.$this->modulename.$id.'.png';
		if (file_exists($path)) return str_replace(IA_ROOT, '..', $path);
		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$this->getAccessToken();
		$params = array();
		$params['scene'] = 'id='.$id;
		$params['page'] = "sharing/pages/frame/frame";
		load()->func('communication');
		$result = ihttp_post($url, json_encode($params));
		$res = json_decode($result['content'],true);
		if ($res['errcode']){
			message('生成错误：'.$result['content']);
		}
		$output = imagecreatefromstring($result['content']);
		imagejpeg($output, $path, 80);
		$path = str_replace(IA_ROOT, '..', $path);
		return $path;
	}
	
	private function getAccessToken() {
		global $_W;
		load()->model('wxapp');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}
	
	private function createZip($link){
		global $_W;
		$filename = date ( 'YmdHis' ) . ".zip";//生成的文件名
		foreach($link as $val){
			$qrs .= $val . ",";
		}
		//打包下载
		include_once IA_ROOT.'/addons/junsion_wifinav/pclzip.lib.php';
		$zip = IA_ROOT."/attachment/wifi".TIMESTAMP.".zip";
		$archive = new PclZip($zip);
		$archive->create($qrs,PCLZIP_OPT_REMOVE_ALL_PATH);
		$fileres = file_get_contents($zip);
		header('Content-type: x-zip-compressed; charset=utf-8');
		header("Content-Type:application/download");
		header('Content-Disposition:attachment;filename="'.$filename.'"');
		echo $fileres;
		unlink($zip);
	}
}
